<template>
  <div class="simple-wave-container">
    <div class="wave-bars">
      <div 
        v-for="(height, index) in bars" 
        :key="index"
        class="wave-bar"
        :style="{ height: height + 'px' }"
      ></div>
    </div>
   
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  barColor: {
    type: String,
    default: '#fff'
  },
  barWidth: {
    type: String,
    default: '8px'
  },
  barCounts: {
    type: Number,
    default: 15
  }
})
// 配置项
const CONFIG = {
  BAR_COUNT: props.barCounts,         // 条形数量
  MIN_HEIGHT: 10,        // 最小高度
  MAX_HEIGHT: 60,        // 最大高度
  UPDATE_INTERVAL: 100   // 更新间隔（毫秒）
}
const isPlaying = ref(false)
const bars = ref(Array(CONFIG.BAR_COUNT).fill(CONFIG.MIN_HEIGHT))
let lastUpdate = 0
let animationFrameId = null

// 生成随机高度
const generateHeights = () => {
  return bars.value.map(() => 
    Math.floor(Math.random() * (CONFIG.MAX_HEIGHT - CONFIG.MIN_HEIGHT)) + CONFIG.MIN_HEIGHT
  )
}

// 平滑过渡动画
const animateBars = (timestamp) => {
  if (!isPlaying.value) return
  
  // 控制更新频率
  if (timestamp - lastUpdate > CONFIG.UPDATE_INTERVAL) {
    const targetHeights = generateHeights()
    bars.value = bars.value.map((current, index) => 
      current + (targetHeights[index] - current) * 0.3
    )
    lastUpdate = timestamp
  }
  
  animationFrameId = requestAnimationFrame(animateBars)
}
// 切换播放状态
const toggleAnimation = () => {
  isPlaying.value = !isPlaying.value
  if (isPlaying.value) {
    animationFrameId = requestAnimationFrame(animateBars)
  }
}
defineExpose({
  toggleAnimation,
})
// 生命周期管理
onMounted(() => {
  if (isPlaying.value) {
    animationFrameId = requestAnimationFrame(animateBars)
  }
})
onUnmounted(() => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
})
</script>
<style scoped>
.simple-wave-container {
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}
.wave-bars {
  display: flex;
  align-items: flex-end;
  height: 100px;
  gap: 8px;
}
.wave-bar {
  width: v-bind('props.barWidth');
  background: v-bind('props.barColor');
  border-radius: 4px 4px 0 0;
  transition: height 0.3s linear;
}
</style>